#!/bin/bash
# Docker容器运行脚本

set -e  # 遇到错误立即退出

echo "🚀 启动边缘云端AI训练系统Docker容器..."

# 容器配置
CONTAINER_NAME="edge-cloud-ai"
IMAGE_NAME="localhost/edge-cloud-ai:latest"
HOST_PORT=${1:-8000}
CONTAINER_PORT=8000

# 数据持久化目录
DATA_DIR="${PWD}/../docker-data"
MODELS_DIR="${DATA_DIR}/models"
DATASETS_DIR="${DATA_DIR}/datasets"
LOGS_DIR="${DATA_DIR}/logs"
TEMP_DIR="${DATA_DIR}/temp"

echo "📦 容器信息:"
echo "  - 容器名称: ${CONTAINER_NAME}"
echo "  - 镜像名称: ${IMAGE_NAME}"
echo "  - 端口映射: ${HOST_PORT}:${CONTAINER_PORT}"
echo "  - 数据目录: ${DATA_DIR}"
echo ""

# 检查Docker是否运行
if ! docker info >/dev/null 2>&1; then
    echo "❌ Docker未运行或无法访问，请检查Docker服务状态"
    exit 1
fi

# 检查镜像是否存在
if ! docker image inspect "${IMAGE_NAME}" >/dev/null 2>&1; then
    echo "❌ 镜像 ${IMAGE_NAME} 不存在，请先运行 ./docker-build.sh 构建镜像"
    exit 1
fi

# 停止并删除已存在的容器
if docker ps -a --format 'table {{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo "🛑 停止并删除已存在的容器..."
    docker stop "${CONTAINER_NAME}" >/dev/null 2>&1 || true
    docker rm "${CONTAINER_NAME}" >/dev/null 2>&1 || true
fi

# 创建数据持久化目录
echo "📁 创建数据持久化目录..."
# mkdir -p "${MODELS_DIR}/cloud" "${MODELS_DIR}/edge" "${MODELS_DIR}/pretrained"
mkdir -p "${DATASETS_DIR}" "${LOGS_DIR}" "${TEMP_DIR}"

# 复制预训练模型（如果存在）
if [ -f "../yolov8n.pt" ]; then
    echo "📋 复制预训练模型..."
    cp -r ../models/pretrained/* "${MODELS_DIR}/pretrained"
fi

# 复制数据集（如果存在）
if [ -d "../datasets" ] && [ "$(ls -A ../datasets)" ]; then
    echo "📋 复制数据集..."
    cp -r ../datasets/* "${DATASETS_DIR}/"
fi

# 运行容器
echo "🔨 启动容器..."
docker run -d \
    --name "${CONTAINER_NAME}" \
    --restart unless-stopped \
    -p "${HOST_PORT}:${CONTAINER_PORT}" \
    -v "${MODELS_DIR}:/app/models" \
    -v "${DATASETS_DIR}:/app/datasets" \
    -v "${LOGS_DIR}:/app/logs" \
    -v "${TEMP_DIR}:/app/temp" \
    -e API_HOST="0.0.0.0" \
    -e API_PORT="${CONTAINER_PORT}" \
    -e LOG_LEVEL="INFO" \
    --memory="4g" \
    --cpus="2.0" \
    "${IMAGE_NAME}"

# 等待容器启动
echo "⏰ 等待容器启动..."
sleep 5

# 检查容器状态
if docker ps --format 'table {{.Names}}\t{{.Status}}' | grep -q "${CONTAINER_NAME}.*Up"; then
    echo "✅ 容器启动成功！"
    echo ""
    echo "📋 容器状态:"
    docker ps --filter "name=${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    echo ""
    echo "🌐 服务访问地址:"
    echo "  - API文档: http://localhost:${HOST_PORT}/docs"
    echo "  - API接口: http://localhost:${HOST_PORT}/api/v1/"
    echo "  - 健康检查: http://localhost:${HOST_PORT}/api/v1/health"
    echo ""
    echo "🔧 管理命令:"
    echo "  查看日志: docker logs -f ${CONTAINER_NAME}"
    echo "  进入容器: docker exec -it ${CONTAINER_NAME} bash"
    echo "  停止容器: docker stop ${CONTAINER_NAME}"
    echo "  删除容器: docker rm -f ${CONTAINER_NAME}"
    echo ""
    echo "💾 数据存储:"
    echo "  - 模型目录: ${MODELS_DIR}"
    echo "  - 数据集目录: ${DATASETS_DIR}"
    echo "  - 日志目录: ${LOGS_DIR}"
else
    echo "❌ 容器启动失败！"
    echo "📝 容器日志:"
    docker logs "${CONTAINER_NAME}"
    exit 1
fi 